package cn.yeamin.ms.commons;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.List;

/**
 * @packageName: 包名: cn.yeamin.ms.commons
 * @classDesc: 类功能描述:(分页实体封装)
 * @author: Administrator
 * @createTime: 2017/7/27 10:29
 * @version: v1.0
 * @copyright:奕明(上海)影视传媒有限公司
 */
@Data
public class PaginationResult {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 当前页的总条数
     */
    private Integer total;

    /**
     * 分页数据
     */
    private List<?> rows;

    public PaginationResult() {
    }

    public PaginationResult(Integer total, List<?> rows) {
        this.total = total;
        this.rows = rows;
    }

    public PaginationResult(Long total, List<?> rows) {
        this.total = total.intValue();
        this.rows = rows;
    }

    /**
     * Object是集合转化
     *
     * @param jsonData json数据
     * @param clazz 集合中的类型
     * @return
     */
    public static PaginationResult formatToList(String jsonData, Class<?> clazz) {
        try {
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("rows");
            List<?> list = null;
            if (data.isArray() && data.size() > 0) {
                list = MAPPER.readValue(data.traverse(),
                        MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
            }
            return new PaginationResult(jsonNode.get("total").intValue(), list);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
